#include "MQTTProxy.h"
#include <QDebug>

CMqttProxy::CMqttProxy(const CConnectOpt& opt, QObject *parent /*= nullptr*/)
	: QObject(parent)
	, m_opt(opt)
{
	initConnect();
}

CMqttProxy::~CMqttProxy()
{
	MQTTAsync_destroy(&m_client);
}

void CMqttProxy::newMessage(const QString& strTopicName, const QString& strMsg)
{
	qDebug() << strTopicName << strMsg;
}

void CMqttProxy::initConnect()
{
	int res = 0;
	QByteArray serverUri = QByteArray("tcp://") + m_opt.strAddress.toLocal8Bit()
		+ QByteArray(":") + QByteArray::number(m_opt.port);
	res = MQTTAsync_create(&m_client, serverUri.data(), m_opt.strClientId.toLocal8Bit().data(), MQTTCLIENT_PERSISTENCE_NONE, NULL);
	if (res != MQTTASYNC_SUCCESS)
	{
		emit sigError("");
		return;
	}
	res = MQTTAsync_setCallbacks(m_client, NULL, connlost, msgarrvd, delivered);
}

void CMqttProxy::delivered(void *pContext, MQTTAsync_token dt)
{
	qDebug() << QString("Message with token value %1 delivery confirmed").arg(dt);
}

int CMqttProxy::msgarrvd(void *pContext, char *pTopicName, int topicLen, MQTTAsync_message *pMessage)
{
	printf("Message arrived:\n");
	printf("    topic: %s\n", pTopicName);
	printf("    message: %.*s\n", pMessage->payloadlen, (char*)pMessage->payload);
	CMqttProxy *pProxy = static_cast<CMqttProxy*>(pContext);
	if (pProxy)
	{
		pProxy->newMessage(QString(pTopicName), QString((char*)(pMessage->payload)));
	}
	MQTTAsync_freeMessage(&pMessage);
	MQTTAsync_free(pTopicName);
	return 0;
}

void CMqttProxy::connlost(void *pContext, char *pCause)
{
	printf("\nConnection lost\n");
	printf("     cause: %s\n", pCause);
}

